'use strict'

const { omit, pick } = require('lodash')

const Service = require('egg').Service

class HouseService extends Service {
    async getHouses() {
        const { model } = this.ctx
        const houses = await model.House.House.findAll({
            limit: 50,
        })
        const _houses = []
        for (const house of houses) {
            const type = await model.House.HouseType.findByPk(parseInt(house.houseType))

            const overview_ids = house.overview.split(',')
            const houseOverview = []
            for (const id of overview_ids) {
                const overview = await model.House.HouseOverview.findByPk(parseInt(id))
                if (overview) {
                    houseOverview.push(overview)
                }
            }

            const res = await model.User.findByPk(parseInt(house.ownerId))
            const owner = pick(res, ['id', 'name', 'star', 'account'])

            _houses.push({
                ...omit(house.dataValues, ['houseType', 'overview', 'ownerId']),
                houseType: type,
                houseOverview,
                owner,
            })
        }
        return _houses
    }
    async getHouseById(id) {
        const house = await this.ctx.model.House.House.findByPk(parseInt(id))
        return house
    }
}

module.exports = HouseService
